<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class User extends CI_Controller {
    
    var $role;
    var $user_id;
    
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('session');
        $this->load->model('users');
        $this->role = $this->session->userdata('role');
        $this->user_id = $this->session->userdata('user_id');
        $this->_authorize();
    }

    public function index() {
        $this->_error();
    }

    private function _error() {
        show_404();
    }

    //AUTHENTICATION//

    private function _authorize() {
        if ($this->session->userdata('islogged') == null) {
            redirect(base_url() . 'cp/login');
        }
    }
    
    private function _is_admin() {
        if ($this->role != 0) {
            $this->_error();
        }
    }

    private function _is_self($user_id) {
        if (($this->user_id != $user_id) && ($this->role != 0)){
            $this->_error();
        }
    }
    
    //BASIC FUNCTION//
    
    public function add(){
        $this->_is_admin();
        $data['name'] = $this->input->post('fname');
        $data['username'] = $this->input->post('fusername');
        $data['password'] = md5($this->input->post('fpassword'));
        $data['role'] = $this->input->post('frole');
        $this->users->insert($data);
        $this->session->set_flashdata('user', 'User Added');
        redirect(base_url() . 'cp/list_user');
    }
    
    public function edit(){
        $user_id = $this->session->userdata('edit_user_id');
        $this->_is_self($user_id);
        $data['name'] = $this->input->post('fname');
        $data['username'] = $this->input->post('fusername');
        if($this->input->post('fpassword') == ''){
            $data['password'] = md5($this->input->post('fpassword'));
        }
        if($this->input->post('frole') != null){
            $data['role'] = $this->input->post('frole');
        }
        $this->users->update_by_id($user_id,$data);
        $this->session->set_flashdata('user', 'User Updated');
        redirect(base_url() . 'cp/list_user');
    }
    
    public function delete($id){
        $this->_is_admin();
        $name = $this->users->get_atribute_by_id('name',$id);
        $this->users->delete($id);
        $this->session->set_flashdata('user', $name.' Deleted');
        redirect(base_url() . 'cp/list_user');
    }

}

?>